package com.ibeacon.service.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import com.ibeacon.controller.common.MessageManager;
import com.ibeacon.model.WeChatUserInfo;
import com.ibeacon.service.WeixinApiService;

@Service("weixinApiService")
public class WeixinApiServiceImpl implements WeixinApiService {

	public WeChatUserInfo getUserInfo(String code, String id,
			HttpServletResponse response) throws Exception {
		System.out.println("**************************************");
		System.out.println("获取到的code值为:" + code);
		System.out.println("获取到的id为：" + id);
		System.out.println("**************************************");
		String appid = MessageManager.getMsg("appid");// "wxb44f389e6eaf1917";
		String secret = MessageManager.getMsg("appsecret");// "e2be14e6b1992acd730187ed85e6f1ad";
		String callurl = java.net.URLEncoder.encode(MessageManager
				.getMsg("wxUrl"), "GBK");// "http://www.winneryun.com/HuiKeWeiXin/login";
		if (code == null || "".equals(code)) {
			String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
					+ appid
					+ "&redirect_uri="
					+ callurl
					+ "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
			WeChatUserInfo weChatUserInfo = new WeChatUserInfo();
			weChatUserInfo.setUrl(url);
			return weChatUserInfo;
			// response.sendRedirect("login?Code=111&id="+id);
		} else {
			System.out.println("service:code值为" + code);
			String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
					+ appid
					+ "&secret="
					+ secret
					+ "&code="
					+ code
					+ "&grant_type=authorization_code";
			System.out.println("**************************************");
			System.out.println("1:" + url + "\n\n\n");
			System.out.println("**************************************");
			String data = getHtmlConentByUrl(url);
			System.out.println("2:" + data + "\n\n\n");
			// String data =
			// "{\"openid\":\"232234dssd23222ww\",\"access_token\":\"ssw22wsw\"}";
			JSONObject jsonObj = JSONObject.fromObject(data);
			String openid = jsonObj.getString("openid");
			// String refresh_token = jsonObj.getString("access_token");
			WeChatUserInfo info = new WeChatUserInfo();
			info.setOpenid(openid);
			String accessToken = jsonObj.getString("access_token");
			// // 判断token是否有效
			// url = "https://api.weixin.qq.com/sns/auth?access_token="
			// + accessToken + "&openid=" + openid;
			// String msg = getHtmlConentByUrl(url);
			// System.out.println("**************************************");
			// System.out.println("判断access_token有效性\n");
			// System.out.println("**************************************");
			// String status = JSONObject.fromObject(msg).getString("errcode");
			// if (!"0".equals(status)) {
			// // 不是有效的token刷新token
			// url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="
			// + appid
			// + "&grant_type=refresh_token&refresh_token="
			// + refresh_token;
			// msg = getHtmlConentByUrl(url);
			// System.out.println("**************************************");
			// System.out.println("2015年11月18日16:22:55刷新access_token\n");
			// System.out.println("**************************************");
			//
			// }
			url = "https://api.weixin.qq.com/sns/userinfo?access_token="
					+ accessToken + "&openid=" + openid + "&lang=zh_CN";
			System.out.println("3:" + url + "\n\n\n");
			String user = getHtmlConentByUrl(url);
			System.out.println("4:" + user + "\n\n\n");
			// String user =
			// "{\"openid\":\"232234dssd23222ww\",\"nickname\":\"jackson\",\"headimgurl\":\"sasqqs.png\"}";
			JSONObject jsonObjUser = JSONObject.fromObject(user);
			info.setOpenid(jsonObjUser.getString("openid"));
			info.setNickname(jsonObjUser.getString("nickname"));
			info.setHeadimgurl(jsonObjUser.getString("headimgurl"));
			System.out.println("获取到的微信名称为："+info.getNickname());
			// info.setOpenid(openid);
			// info.setNickname("");
			// info.setHeadimgurl("");
			return info;
		}
	}

	// 获取页面内容
	public static String getHtmlConentByUrl(String ssourl) {
		try {
			URL url = new URL(ssourl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setInstanceFollowRedirects(false);
			con.setUseCaches(false);
			con.setAllowUserInteraction(false);
			con.connect();
			StringBuffer sb = new StringBuffer();
			String line = "";
			BufferedReader URLinput = new BufferedReader(new InputStreamReader(
					con.getInputStream(),"utf-8"));
			while ((line = URLinput.readLine()) != null) {
				sb.append(line);
			}
			con.disconnect();
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}